package com.lunevich.json.activity;

import java.util.List;

import org.json.JSONObject;

import com.lunevich.json.R;
import com.lunevich.json.adapter.TwitterAdapter;
import com.lunevich.json.tasks.JSONObjectAsyncTask;
import com.lunevich.json.wrappers.TwitterWrapper;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.ProgressBar;

public class JsonObjectActivity extends Activity {
	
	 // url to make request
//    private String url = "http://search.twitter.com/search.json?q=android";
	private String url = "http://dl.dropbox.com/u/16403954/bm.json";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.list);
        
        final ListView list = (ListView) findViewById(R.id.listView);
        final ProgressBar loading = (ProgressBar) findViewById(R.id.preload);
		
		new JSONObjectAsyncTask<TwitterWrapper>(this){

			@Override
			public void onLoadSuccess(List<TwitterWrapper> contactList) {
				TwitterAdapter jsonAdapter = new TwitterAdapter(JsonObjectActivity.this,  contactList);
				list.setAdapter(jsonAdapter);
				loading.setVisibility(View.INVISIBLE);
			}

			@Override
			public void onLoadError(Exception exception) {
				showErrorDialog(exception);
				loading.setVisibility(View.INVISIBLE);
			}

			@Override
			public TwitterWrapper createWrapper(JSONObject object) {
				return new TwitterWrapper(object);
			}
			
		}.execute(url);
    }
    
    private void showErrorDialog(Exception exception) {
    	AlertDialog.Builder builder = new AlertDialog.Builder(JsonObjectActivity.this);
		builder.setMessage(exception.getMessage() + ".   EXIT ? ")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   JsonObjectActivity.this.finish();
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
    }
}